package com.sky.service.impl;

import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;


    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //获取日期范围
        List<String> dateList = generateDateRange(begin, end);
        //获取mount 格式为2014-7-11&11.0
        List<String> getTurnoverByDateRange = reportMapper.getTurnoverByDateRange(begin, end);
        //构建实例
        String turnoverListResult = processDateList(dateList, getTurnoverByDateRange);
        TurnoverReportVO result = TurnoverReportVO.builder().turnoverList(turnoverListResult).dateList(String.join(",", dateList)).build();

        return result;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取日期范围
        List<String> dateList = generateDateRange(begin, end);
        List<String> totalUserList = reportMapper.getTotalUserList(begin, end);
        List<String> newUserList = reportMapper.getNewUserList(begin, end);
        String totalUserListResult = processDateList(dateList, totalUserList);
        String newUserListResult = processDateList(dateList, newUserList);
        UserReportVO userReportVOResult = UserReportVO.builder().dateList(String.join(",", dateList)).totalUserList(totalUserListResult).newUserList(newUserListResult).build();
        return userReportVOResult;
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //获取日期范围
        List<String> dateList = generateDateRange(begin, end);
        List<String> orderCountList = reportMapper.getOrderCountList(begin, end);
        List<String> validOrderCountList = reportMapper.getValidOrderCountList(begin, end);
        Integer totalOrderCount = reportMapper.getTotalOrderCount(begin, end);
        Integer validOrderCount = reportMapper.getValidOrderCount(begin, end);


        double percentage = (double) validOrderCount / totalOrderCount;
        String orderCountListResult = processDateList(dateList, orderCountList);
        String validOrderCountResult = processDateList(dateList, validOrderCountList);
        OrderReportVO OrderReportVOResult = OrderReportVO.builder().orderCountList(orderCountListResult).validOrderCountList(validOrderCountResult).totalOrderCount(totalOrderCount).validOrderCount(validOrderCount).dateList(String.join(",", dateList)).orderCompletionRate(percentage).build();
        return OrderReportVOResult;
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        List<Top10ItemVO> getTop10List = reportMapper.getTop10List(begin, end);
        //将getTop10List数据写成两个String类型的字符串,1.商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼,2.销量列表，以逗号分隔，例如：260,215,200
        StringBuilder nameList = new StringBuilder();
        StringBuilder numberList = new StringBuilder();
        for (Top10ItemVO map : getTop10List) {
            nameList.append(map.getName()).append(",");
            numberList.append(map.getTotalSales().toString()).append(",");
        }
        // 去掉最后一个多余的逗号
        if (nameList.length() > 0) {
            nameList.setLength(nameList.length() - 1);
        }
        if (numberList.length() > 0) {
            numberList.setLength(numberList.length() - 1);
        }
        return SalesTop10ReportVO.builder().nameList(nameList.toString()).numberList(numberList.toString()).build();

    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询总订单数
        Integer totalOrderCount = reportMapper.getTotalOrderCount(begin, end);
        //TODO 营业额
        List<String> getTurnoverByDateRange = reportMapper.getTurnoverByDateRange(begin, end);
        double turnover = 0.0;
         for (String entry : getTurnoverByDateRange) {
            String[] parts = entry.split("&");
            if (parts.length > 1) {
                turnover += Double.parseDouble(parts[1]);
            }
        }
        //TODO 有效订单数
        Integer validOrderCount = reportMapper.getValidOrderCount(begin, end);
        //TODO 新增用户数
        List<String> newUserList = reportMapper.getNewUserList(begin, end);
        Integer newUsers = 0;
        for (String s : newUserList) {
            String[] parts = s.split("&");
            if (parts.length > 1) {
                newUsers += Integer.valueOf(parts[1]);
            }
        }
        Double unitPrice = 0.0;

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0 && validOrderCount != 0) {
            //订单完成率
            orderCompletionRate = Double.valueOf(String.format("%.2f",validOrderCount.doubleValue() / totalOrderCount));
            //平均客单价
            unitPrice = Double.valueOf(String.format("%.2f", turnover / validOrderCount));
        }
//        excel创建
        //通过POI将数据写入excel中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/模板文件.xlsx");
        try {
            //基于模板创建新文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("测试info");
            sheet1.getRow(2).getCell(0).setCellValue("时间:" + begin + "至" + end);
            //TODO 数据有问题,导出功能没问题

            sheet1.getRow(4).createCell(1).setCellValue(turnover);
            sheet1.getRow(4).createCell(3).setCellValue(orderCompletionRate);
            sheet1.getRow(4).createCell(5).setCellValue(newUsers);
            sheet1.getRow(5).createCell(1).setCellValue(validOrderCount);
            sheet1.getRow(5).createCell(3).setCellValue(unitPrice);
            //通过输出流将excel文件下载到客户端
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //    计算日期
    public static List<String> generateDateRange(LocalDate begin, LocalDate end) {
        long daysBetween = ChronoUnit.DAYS.between(begin, end) + 1;
        return LongStream.range(0, daysBetween)
                .mapToObj(i -> begin.plusDays(i))
                .map(LocalDate::toString)
                .collect(Collectors.toList());
    }

    public String processDateList(List<String> dateList, List<String> getTurnoverByDateRange) {
        StringBuilder result = new StringBuilder();
        Map<String, String> turnoverMap = new HashMap<>();

        // 将 getTurnoverByDateRange 的结果转换为 Map，便于快速查找
        for (String turnover : getTurnoverByDateRange) {
            String[] parts = turnover.split("&");
            if (parts.length == 2) {
                turnoverMap.put(parts[0], parts[1]);
            }
        }

        // 遍历 dateList，根据 Map 查找对应的金额
        for (int i = 0; i < dateList.size(); i++) {
            String date = dateList.get(i);
            String amount = turnoverMap.getOrDefault(date, "0.0");
            result.append(amount);
            if (i < dateList.size() - 1) {
                result.append(",");
            }
        }

        return result.toString();
    }

}
